import React from "react";
import { useState, useEffect } from "react";
import { Editor,  } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import { EditorState, convertToRaw, ContentState } from 'draft-js';


export default function NewsEditor({onContentChange, content}) {
    const [editorState, setEditorState] = useState(EditorState.createEmpty());
    useEffect(() => {
        console.log(content);
        if (!content)
            return;
        const contentBlock = htmlToDraft(content);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const newEditorState = EditorState.createWithContent(contentState);
            setEditorState(newEditorState);
        }
    }, [content]);
    
    return (
        <Editor
            editorState={editorState}
            onEditorStateChange={setEditorState}
            onBlur={() => onContentChange(draftToHtml(convertToRaw(editorState.getCurrentContent())))}
        />
    );
}
